from datetime import datetime
import logging

from fastapi import APIRouter, UploadFile, Depends, File, Form, Query
from fastapi.responses import FileResponse
from pathlib import Path
import shutil

from sqlalchemy.orm import Session

from app.config import config
from app.web.models.Database import get_db
from app.web.models.JobSeeker import JobSeeker, Resume
from app.web.models.Recruiter import JobPostResume, JobPost, ResumeReport
from app.web.routers.Schemas import ResumeSchema

logger = logging.getLogger(__name__)
file_cache_path = config.root_path / "tests" / "cache"
router = APIRouter()


@router.get("/resume")
async def get_resume(job_seeker_id: int = Query(None), db: Session = Depends(get_db)):
    job_seeker = db.query(JobSeeker).filter(JobSeeker.id == job_seeker_id).first()
    resumes = []
    if job_seeker is not None:
        for resume in db.query(Resume).all():
            resumes.append(ResumeSchema(id=resume.id, fileName=resume.file_name,
                                        createdAt=resume.created_at.strftime("%Y-%m-%d %H:%M:%S")))
    return resumes


@router.post("/uploadResume")
async def upload_resume(job_seeker_id: int = Form(), file: UploadFile = File(...), db: Session = Depends(get_db)):
    job_seeker = db.query(JobSeeker).filter(JobSeeker.id == job_seeker_id).first()
    if job_seeker is None:
        raise Exception("找不到候选人信息")
    base_path = file_cache_path / f"job_seeker_{job_seeker_id}"
    if not Path.exists(base_path):
        Path.mkdir(base_path)
    file_location = base_path / f"{file.filename}"
    logger.info(f"file_location: {file_location}")
    old_resume = db.query(Resume).filter(Resume.job_seeker == job_seeker_id, Resume.file_name == file.filename).first()
    if old_resume is not None:
        old_resume.version += 1
        old_resume.created_at = datetime.now()
        old_resume.file_path = str(file_location)
        if file_location.exists():
            file_location.unlink()
        with open(file_location, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
        db.commit()
        return old_resume
    else:
        with open(file_location, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
        resume = Resume(file_name=file.filename, file_path=str(file_location), job_seeker=job_seeker_id)
        db.add(resume)
        db.commit()
        db.refresh(resume)
        return resume


@router.post("/applyJobPost")
async def apply_job_post(job_post_id: int = Form(), resume_id: int = Form(), job_seeker_id: int = Form(),
                         db: Session = Depends(get_db)):
    job_post = db.query(JobPost).get(job_post_id)
    if job_post is None:
        raise Exception("找不到对应的工作岗位")
    resume: Resume = db.query(Resume).get(resume_id)
    if resume is None or resume.job_seeker != job_seeker_id:
        raise Exception("找不到对应的简历")
    job_post_resume = JobPostResume(job_post=job_post_id, resume=resume_id)
    db.add(job_post_resume)
    db.flush()
    db.refresh(job_post_resume)
    job_resume_report = ResumeReport(job_post_resume=job_post_resume.id)
    db.add(job_resume_report)
    db.commit()
    db.refresh(job_post_resume)
    return job_resume_report


@router.get("/downloadResume")
async def download_resume(job_seeker_id: int = Query(None), resume_id: int = Query(None),
                          db: Session = Depends(get_db)):
    job_seeker: JobSeeker = db.query(JobSeeker).get(job_seeker_id)
    if job_seeker is None:
        raise Exception("找不到申请人信息")
    resume: Resume = db.query(Resume).get(resume_id)
    if resume is None:
        raise Exception("找不到简历信息")
    if resume.job_seeker != job_seeker_id:
        raise Exception("查看的申请人和简历信息匹配错误")

    return FileResponse(path=resume.file_path, media_type="application/pdf", filename=resume.file_name,
                        content_disposition_type="inline")


@router.get("/testUser")
async def get_test_user(db: Session = Depends(get_db)):
    return db.query(JobSeeker).first()
